package com.google.samples.apps.paging.data

import androidx.paging.PageKeyedDataSource
import com.google.samples.apps.library_common.utils.LogUtils
import com.google.samples.apps.paging.data.bean.GoodsBean
import com.google.samples.apps.paging.data.bean.GoodsListBean
import com.google.samples.apps.paging.http.BaseBean
import com.google.samples.apps.paging.http.HttpBody
import com.google.samples.apps.paging.http.apiService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * Created by Administrator on 2021/7/10 0010.
 * Describe:
 */
class GoodsDataSource : PageKeyedDataSource<Int, GoodsBean>() {
    companion object {
        const val KEY_PAGE = "page"
        const val KEY_SIZE = "size"
        var FIRST_PAGE = 1
        var SIZE_PAGE = 10
    }

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, GoodsBean>
    ) {
        val body = HttpBody.getBody()
            .add(KEY_PAGE, FIRST_PAGE)
            .add(KEY_SIZE, SIZE_PAGE)
        apiService.getGoodsHome(body.toJson())
            .enqueue(object : Callback<BaseBean<GoodsListBean>> {
                override fun onResponse(
                    call: Call<BaseBean<GoodsListBean>>,
                    response: Response<BaseBean<GoodsListBean>>
                ) {
                    LogUtils.d(FIRST_PAGE)
                    response.body()?.data?.let {
                        callback.onResult(it?.proList, null, FIRST_PAGE + 1)
                    }
                }

                override fun onFailure(call: Call<BaseBean<GoodsListBean>>, t: Throwable) {
                    LogUtils.e(t)
                }

            })
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, GoodsBean>) {
        val body = HttpBody.getBody()
            .add(KEY_PAGE, params.key)
            .add(KEY_SIZE, SIZE_PAGE)
        apiService.getGoodsHome(body.toJson())
            .enqueue(object : Callback<BaseBean<GoodsListBean>> {
                override fun onResponse(
                    call: Call<BaseBean<GoodsListBean>>,
                    response: Response<BaseBean<GoodsListBean>>
                ) {
                    LogUtils.d(params.key)
                    val listSize = response.body()?.data?.proList?.size ?: 0
                    val hasMore = listSize >= SIZE_PAGE
                    val nextKey: Int? = if (hasMore) params.key + 1 else null
                    callback.onResult(response.body()?.data?.proList ?: mutableListOf(), nextKey)

                }

                override fun onFailure(call: Call<BaseBean<GoodsListBean>>, t: Throwable) {
                    LogUtils.e(t)
                }

            })

    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, GoodsBean>) {
        LogUtils.d(params.key)
    }
}